package com.miguo.http.callback;

import android.app.Activity;

import com.miguo.app.AppContext;
import com.miguo.framework.request.FailData;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.request.RequestJsonHandler;
import com.miguo.framework.utils.Toast;
import com.miguo.framework.view.LoadingDialog;

/**
 * 请求回调类
 */
public class AjaxCallBack extends RequestJsonHandler {


    private Activity mActivity;
    private LoadingDialog loadingDialog;
    private String message;
    private boolean isInitShow = true;

    public AjaxCallBack(Activity activity) {
        this(activity, null);
    }

    public AjaxCallBack(Activity activity,boolean isInitShow) {
        this(activity, null,isInitShow);
    }

    public AjaxCallBack(Activity activity, String message) {
        this(activity,message,true);
    }

    public AjaxCallBack(Activity activity,String message,boolean isInitShow){
        this.mActivity = activity;
        this.message = message;
        this.isInitShow = isInitShow;
        this.init();
    }

    private void init() {
        loadingDialog = new LoadingDialog(mActivity);
        loadingDialog.setMessage(message);
        if(isInitShow) loadingDialog.show();
    }

    private void dismiss() {
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    public void show() {
        loadingDialog.show();
    }

    public void hideDialog(){
        if(loadingDialog!=null && loadingDialog.isShowing())
            loadingDialog.dismiss();
    }

    @Override
    public JsonData processOriginData(JsonData jsonData) {
        return jsonData;
    }

    @Override
    public void onRequestStart() {
    }

    @Override
    public void onRequestFinish(JsonData data) {
        dealStatus(data);
        dismiss();
    }

    private void dealStatus(JsonData data) {
        switch (data.optInt("status")) {
            case 200:
                break;
            case 401:
                AppContext.UserInfo().Logout();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestFail(FailData data) {
        Toast.show(AppContext.getContext(), "请求失败,请稍后重试!");
//        switch (data.getErrorType()) {
//            case 0://未知错误
//                Toast.show(mActivity,"未知错误");
//                break;
//            case 1://输入错误
//                Toast.show(mActivity,"输入错误");
//                break;
//            case 2://网络错误
//                Toast.show(mActivity,"网络错误");
//                break;
//            case 3://数据格式错误
//                Toast.show(mActivity,"数据格式错误");
//            default:
//                Toast.show(mActivity,"加载失败，请刷新重试");
//                break;
//        }
        dismiss();
    }

}
